<template>
  <div class="pages">
    <!-- 头部导航 -->
		<div class="header animate__fadeInDown">
			<button class="back-button fff" @click="router.back()">
				<span class="back-icon">←</span>
			</button>
			<span class="header-title fff">{{routerTitle}}设置</span>
		</div>
    <div class="control-pages">
      <!-- DeepSeek触发时长 -->
      <div class="content animate__fadeInUp">
        <div class="title">DeepSeek触发时长</div>
        <div class="sub-title">默认2秒，可按直播习惯改成合适的参数</div>
        <div class="input-block-one">
          <input type="text" v-model="form.dsSpace" placeholder="2"/>
          <div class="unit">秒</div>
        </div>
      </div>
      <div class="content animate__fadeInUp">
        <div class="title">
          <!-- <div class="require">*</div> -->
          <div class="text">ARK_API_KEY</div>
        </div>
        <input type="text" v-model="form.dsApiKey" placeholder="请输入"/>
      </div>
      <div class="content animate__fadeInUp">
        <div class="title">
          <!-- <div class="require">*</div> -->
          <div class="text">model</div>
        </div>
        <input type="text" v-model="form.dsModel" placeholder="请输入"/>
      </div>

      <div class="deepseek-items animate__fadeInUp animate__delay-2">
        <div class="deepseek-items-title">
          <div class="text">告诉我您希望AI扮演的角色</div>
        </div>
        <div class="textarea-block">
          <textarea maxlength="-1" class="textarea" placeholder-style="color: #BFBFBF;"  v-model="form.zpUser" placeholder="请输入"></textarea>
        </div>
        <!-- <div class="button-block">
          <button @click="toTest">AI测试</button>
          <button @click="updateDeepseek">开始/更新角色</button>
        </div> -->
      </div>

      <div style="height: 57px;"></div>
      <div class="btn-block">
        <button class="live-btn position" @click="submitChanges">保存修改</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { dialog } from '@/utils/dialog'
import { useStore } from '@/stores/data'
import { useRouter, useRoute } from 'vue-router';

const router = useRouter();
const store = useStore()


// 使用query参数
const routerName = ref(useRoute().query.name)
const routerTitle = ref(useRoute().query.title)

// 本地表单（直接拷贝后端对象）
const form = reactive<any>({})
// 原始快照（用于 diff）
const original = ref<any>({})

// 深拷贝
const cloneDeep = (obj: any) => JSON.parse(JSON.stringify(obj))

// 初始化
onMounted(async () => {
  await store.getConfig()
  initForm()
})

function initForm() {
  const src = cloneDeep(store.userConfig || {})
  Object.keys(src).forEach(k => (form[k] = src[k]))
  original.value = cloneDeep(src)
  console.log(original)
}

// ============ 提交前的转换逻辑 ============


// 仅提交变化字段
function isEqual(a: any, b: any) {
  return JSON.stringify(a) === JSON.stringify(b)
}

function diffObject(curr: any, base: any) {
  const out: any = {}
  const keys = new Set([...Object.keys(curr || {}), ...Object.keys(base || {})])
  keys.forEach(k => {
    if (!isEqual(curr[k], base[k])) out[k] = curr[k]
  })
  return out
}

async function submitChanges() {
  // 先构造“提交时的规范对象”（对 *Txt / mainTxt / mainTxtSpace 执行转换）
  const current = cloneDeep(form)

  // 只提交有变化的字段
  const changes = diffObject(current, original.value)
  if (Object.keys(changes).length === 0) {
    // dialog.alert({message: '没有改动需要提交'});
    router.back()
    return
  }

  try {
    await store.updateConfig(changes)
    // 刷新基线
    Object.keys(current).forEach(k => (form[k] = current[k]))
    original.value = cloneDeep(current)
    store.getConfig()
    dialog.alert({ iconType: 'sc', message: '已提交修改'}).then(() => {
      router.back()
    });
  } catch (e: any) {
    console.error(e)
    dialog.alert({message: e?.message || '提交失败'});
  }
}
</script>

<style lang="scss" scoped>
@import './config.scss';
.content {
  .title {
    display: flex;
    // margin-bottom: 14px;
    .require {
      color: #FF3E3E;
      margin-right: 5px;
      font-weight: 600;
      font-size: 16px;
    }
    
    .text {
      font-family: PingFang SC, PingFang SC;
      font-weight: 600;
      font-size: 14px;
      color: #303E52;
    }
  }
  
  input {
    width: 100%;
    border-radius: 8px;
    font-family: PingFang SC, PingFang SC;
    font-size: 14px;
    color: #00042D;
    height: 49px;
    line-height: 49px;
    padding: 0 16px;
    background: #FFFFFF;
    box-sizing: border-box;
    border: 1px solid #DAE2EA;
  }
}
// deepseek
.deepseek {
  background: #E4F2FD;
  padding: 20px 16px; // 35rpx / 1.7441 = 20px, 28rpx / 1.7441 = 16px
  border-radius: 20px; // 35rpx / 1.7441 = 20px
  box-sizing: border-box;
  &-items {
    padding: 20px; // 35rpx / 1.7441 = 20px
    background: #FFFFFF;
    border-radius: 10px; // 17rpx / 1.7441 = 10px
    margin-bottom: 20px; // 35rpx / 1.7441 = 20px
    &-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .text {
        font-family: PingFang SC, PingFang SC;
        font-weight: 600;
        font-size: 16px; // 28rpx / 1.7441 = 16px
        color: #00042D;
      }
    }
    .textarea-block {
      margin-top: 15px; // 26rpx / 1.7441 = 15px
      height: 206px; // 359rpx / 1.7441 = 206px
      background: #FFFFFF;
      border: 1px solid #DAE2EA; // 2rpx / 1.7441 = 1px
      width: 100%;
      border-radius: 8px; // 14rpx / 1.7441 = 8px
      box-sizing: border-box;
      margin-bottom: 16px; // 28rpx / 1.7441 = 16px
      textarea {
        background: #ffffff;
        width: 100%;
        height: 100%;
        box-sizing: border-box;
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        font-size: 14px; // 24rpx / 1.7441 = 14px
      }
    }
    .button-block {
      display: flex;
      justify-content: space-between;
      button {
        width: 167px; // 291rpx / 1.7441 = 167px
        height: 44px; // 77rpx / 1.7441 = 44px
        display: flex;
        align-items: center;
        justify-content: center;
        text-align: center;
        border-radius: 22px; // 38rpx / 1.7441 = 22px
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 16px; // 28rpx / 1.7441 = 16px
      }
      button:first-child {
        background: rgba(0,108,255,0.1);
        border: 1px solid #006CFF !important; // 2rpx / 1.7441 = 1px
        color: #006CFF;
      }
      button:last-child {
        color: #ffffff;
        background: linear-gradient( 90deg, #006CFF 0%, #009FFF 100%);
      }
    }
  }
}
</style>